package com.gitee.wsl.jvm.okhttp.intercept.token

import com.gitee.wsl.jvm.okhttp.OkHttpClientScope
import com.gitee.wsl.jvm.okhttp.exception.ResponseStatusException
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 客户端token自动续期示例
 */
class RefreshTokenInterceptor(val config: TokenConfig) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        return synchronized(RefreshTokenInterceptor::class.java) {
            if (response.code == 401 && config.isLogin() && !config.isTokenPath(request.url.encodedPath)){//request.url.encodedPath.contains(Token)) {
                //val tokenInfo = Net.get(Api.Token).execute<Token>() // 同步请求token
                val tokenInfo = config.refresh()
                if (tokenInfo.isExpired) {
                    // token过期抛出异常, 由全局错误处理器处理, 在其中可以跳转到登陆界面提示用户重新登陆
                    throw ResponseStatusException(response.code, "登录状态失效")
                } else {
                    config.saveToken(tokenInfo)
                }
                chain.proceed(request)
            } else {
                response
            }
        }
    }

    companion object{
        const val Token = "/token"
    }

}

interface TokenConfig{

    fun isLogin():Boolean

    fun isTokenPath(path:String):Boolean

    fun refresh():Token

    fun login():Token

    fun getToken():Token?

    fun saveToken(token: Token)

}

fun OkHttpClientScope.refreshToken(config: TokenConfig){
    getBuilder().addInterceptor(RefreshTokenInterceptor(config))
}